package cn.wen.forum.common.exception;

import cn.wen.forum.common.result.JSONResult;
import cn.wen.forum.common.result.Result;
import org.elasticsearch.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName GlobalExceptionHandler
 * @Author By wen
 * @Description 全局异常处理
 * @Date 2023/7/6 16:53
 * @Version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = { ResourceNotFoundException.class })
    @ResponseBody
    public JSONResult handleResourceNotFoundException(ResourceNotFoundException ex) {
        // 记录异常信息到日志文件
        logger.error("Resource not found: ", ex);
        // 返回HTTP错误代码和异常信息
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler(value = { ServiceException.class })
    @ResponseBody
    public JSONResult handleException(ServiceException ex) {
        // 记录异常信息到日志文件
        logger.error("业务异常: ", ex);
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler(value = { Exception.class })
    @ResponseBody
    public JSONResult handleException(Exception ex) {
        // 记录异常信息到日志文件
        logger.error("程序异常: ", ex);
        return Result.fail(ex.getMessage());
    }

}
